<script setup>
import {Delete, Edit, Plus} from '@element-plus/icons-vue'
import {ref} from 'vue'
import { 
  taskPageService,
  cancelTaskService,
  deleteTaskService,
  getAllEmployee,
  addTaskService
} from "@/api/task";

import {ElMessage, ElMessageBox} from "element-plus";

//用户搜索时的任务名称
const taskName = ref('')
//任务数据模型
const task = ref([])
//添加任务数据模型
const employees = ref([]);
const taskData = ref({
  taskName: '',
  assignee: '',
  description: '',
})
//控制抽屉是否显示
const dialogVisible = ref(false)
//控制编辑框标题，为添加任务or修改任务
const title = ref('')
//分页条数据模型
const page = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(10)//每页条数

// 状态选项
const statusOptions = [
  { label: '未开始', value: 0 },
  { label: '进行中', value: 1 },
  { label: '已完成', value: 2 },
  { label: '已取消', value: 3 }
]

 //当每页条数发生了变化，调用此函数
 const onSizeChange = (size) => {
  pageSize.value = size
  getTaskList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  page.value = num
  getTaskList()
}
 //定义注册表单校验规则
 const rules ={
  taskName:[
    {required:true, message:"请输入任务名称", trigger:"blur"},
  ]
}
//清空模型数据
const clearData = () => {
  departmentData.value.departmentName = '';
  departmentData.value.departmentDescription = '';
}
//获取分页任务列表
const getTaskList = async () => {
  const params = {
    page: page.value,
    pageSize: pageSize.value,
    taskName: taskName.value? taskName.value : null,
  }
  try {
    const result = await taskPageService(params);
    console.log('获取任务列表结果:', result);
    
    if (result.code === 0 && result.data) {
      // 正确设置总记录数
      total.value = result.data.total || 0;
      task.value = result.data.records?.map(item => ({
       ...item,
        statusLabel: statusOptions.find(s => s.value === item.status)?.label || '未知状态',
      })) || [];
    } else {
      ElMessage.error(result.message || '获取任务列表失败')
    }
  } catch (error) {
    console.error('获取任务列表错误:', error);
    ElMessage.error('网络错误，请稍后重试')
  }
}

getTaskList()

//添加任务
const addTask = async () => {
  const result = await addTaskService(taskData.value);

  ElMessage({
      showClose: true,
      message: result.msg ? result.msg : "添加成功",
      type: 'success',
    })
  dialogVisible.value = false
  getTaskList()
}

//撤销任务
const cancelTask = async (taskId) => {
    const result = await cancelTaskService(taskId)
    ElMessage({
      showClose: true,
      message: result.msg ? result.msg : "撤销成功",
      type: 'success',
    })
      getTaskList()
}

const deletTask = (row) => {
  ElMessageBox.confirm(
      '你确认要删除该任务信息吗？',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(
    async () => {
      const result = await deleteTaskService(row.id)
      ElMessage({
      showClose: true,
      message: result.msg ? result.msg : "删除成功",
      type: 'success',
    })
    getTaskList()
  }
  )
}

// 获取员工列表
const fetchEmployees = async () => {
    const res = await getAllEmployee() 
    console.log(res.code);
      employees.value = res.data.map(({ id, userName }) => ({
        id,
        userName,
      }));
};
fetchEmployees();
</script>
<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>任务管理</span>
        <div class="extra">
          <el-button type="primary" @click="dialogVisible=true;title='创建任务';clearData()">创建任务</el-button>
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="任务名称" style="width: 180px;">
    <el-input v-model.number="taskName"></el-input>
  </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getTaskList">搜索</el-button>
        <el-button @click="taskName=''">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 部門列表 -->
    <el-table :data="task" style="width: 100%">
      <el-table-column prop="taskName" label="任务名称" width="150"/>
      <el-table-column prop="assignorName" label="发布人" width="130"/>
      <el-table-column prop="assigneeName" label="负责人" width="130"/>
      <el-table-column prop="description" label="任务描述" width="200"/>
      <el-table-column prop="statusLabel" label="状态" width="120">
        <template #default="{row}">
          <el-tag 
            :type="row.status === 1? 'info' : row.status === 2? 'success' : row.status === 3? 'danger' : 'warning'"
            effect="plain"
          >
            {{ row.statusLabel }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180"/>
      <el-table-column prop="updateTime" label="更新时间" width="180"/>
      <el-table-column label="操作" width="130">
    <template #default="{row}">
        <div style="display: flex; justify-content: flex-end; gap: 10px">
            <el-button
                v-if="row.status!== 2"
                type="danger"
                size="small"
                @click="cancelTask(row.id)"
            >
                取消
            </el-button>
            <el-button
                type="danger"
                size="small"
                @click="deletTask(row)"
            >
                删除
            </el-button>
        </div>
    </template>
</el-table-column>
      <template #empty>
        <el-empty description="没有数据"/>
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[3, 5 ,10, 15]"
                   layout="jumper, total, sizes, prev, pager, next" background :total="total"
                   @size-change="onSizeChange"
                   @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end"/>
  </el-card>


  <!-- 抽屉 -->
  <el-drawer v-model="dialogVisible" :title="title" direction="rtl" size="50%">
    <!-- 添加部門表单 -->
    <el-form :model="taskData" label-width="100px" :rules="rules">
      <el-form-item label="任务名称" prop="taskName">
        <el-input v-model="taskData.taskName" placeholder="请输入任务名称"></el-input>
      </el-form-item>
      <el-form-item label="任务描述">
        <el-input v-model="taskData.description" placeholder="请输入任务描述"></el-input>
      </el-form-item>
      <el-form-item label="负责人" prop="assignee">
          <el-select
            v-model="taskData.assignee"
            placeholder="请选择负责人"
            :disabled="!employees.length"
          >
            <el-option
              v-for="emp in employees"
              :key="emp.id"
              :label="emp.userName"
              :value="emp.id"
            />
          </el-select>
        </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addTask()">保存
        </el-button>
        <el-button type="info" @click="dialogVisible = false" style="">取消
        </el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}


/* 抽屉样式 */
.avatar-uploader {
  :deep {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;

  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>